///\todo upgrade

//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//  This file is part of the buola project (https://code.google.com/p/buola/).  //
//                                                                              //
//  Copyright(c) 2007-2012 Xavi Gratal                                          //
//  gratal AT gmail DOT com                                                     //
//                                                                              //
//  Buola is free software: you can redistribute it and/or modify               //
//  it under the terms of the GNU General Public License as published by        //
//  the Free Software Foundation, either version 3 of the License, or           //
//  (at your option) any later version.                                         //
//                                                                              //
//  Buola is distributed in the hope that it will be useful,                    //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of              //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               //
//  GNU General Public License for more details.                                //
//                                                                              //
//  You should have received a copy of the GNU General Public License           //
//  along with buola.  If not, see <http://www.gnu.org/licenses/>.              //
//                                                                              //
//////////////////////////////////////////////////////////////////////////////////

#ifndef _BUOLA_BBOX_PROTOCOL_CCONNECTIONBASE_H_
#define _BUOLA_BBOX_PROTOCOL_CCONNECTIONBASE_H_

#include <buola/bbox/protocol/cpacket.h>
#include <buola/bbox/protocol/enums.h>
#include <buola/io/csocket.h>
#include <buola/io/cpacketreader.h>

namespace buola { namespace bbox { namespace protocol {

class CConnectionBase
{
protected:
    CConnectionBase(io::PSocket pSocket,const std::string &pName);

public:
    virtual ~CConnectionBase();

public:
    uint32_t SendPacket(CPacket &pPacket);
    void SendError(const CPacket &pReplyTo,EError pError);
    std::unique_ptr<CPacket> ReadPacket(bool pBlock);

    const io::PSocket& Socket()    {   return mSocket; }
    bool AtEOF()                                    {   return mPacketReader.AtEOF();   }
    
private:
    virtual void OnHello(const std::string &pPeerName) {}

    void SendHello(const std::string &pName);

private:    
    bool mHelloReceived;

    uint32_t mNextOwnSeq;
    uint32_t mNextPeerSeq;

    std::unique_ptr<CPacket> mPartial;
    size_t mPartialPos;
    
    io::PSocket mSocket;
    io::CPacketReader<CPacket> mPacketReader;
};

/*namespace protocol*/ } /*namespace bbox*/ } /*namespace buola*/ }

#endif
